﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Medianamik.Core.DAL.SQL;
using Medianamik.Core.Interfaces;

namespace Medianamik.Core.DAL
{
    public class GetNodeCountCommandBuilder
    {
        private ParameterNameGenerator _paramGenerator = new ParameterNameGenerator();
        private JoinNameGenerator _joinGenerator = new JoinNameGenerator();

        protected SubSonic.DataProvider Provider
        {
            get;
            private set;
        }

        public GetNodeCountCommandBuilder(SubSonic.DataProvider pSubsonicDataProvider)
        {
            Provider = pSubsonicDataProvider;
        }


        public SubSonic.QueryCommand Build(IQueryDefinition pQueryDef)
        {
            var queryParams = default(IEnumerable<IParameter>);

            var rowNumberQuery = new RowNumberQueryBuilder(pQueryDef, _paramGenerator, _joinGenerator)
                .Build(out queryParams, false);

            var finalQuery = new StringBuilder()
            .AppendLine(";WITH NodeIds as ( ")
            .Append(rowNumberQuery.ToSQL())
            .Append(" ) SELECT COUNT(*) FROM NodeIds");

            var command = new SubSonic.QueryCommand(finalQuery.ToString(), Provider.Name);
            foreach (var p in queryParams)
            {
                command.Parameters.Add(p.Name, p.Value);
            }
            return command;

        }



    }
}
